<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px"
             class="searchFrom">
      <el-row>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="项目名称" prop="projectName">
            <el-input maxlength="50"
                      class="search-width"
                      v-model="queryParams.projectName"
                      placeholder="请输入项目名称"
                      clearable
                      @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="所属板块" prop="sectorAll">
            <el-cascader filterable clearable
                         class="search-width"
                         v-model="queryParams.sectorAll"
                         :options="bizSectorList"
                         :props="{value: 'id', label: 'name', checkStrictly: true}"
                         :show-all-levels="false"
                         placeholder="请选择所属板块"
                         @change="handleParamSector"/>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="项目类型" prop="classifyCode">
            <el-select filterable clearable
                       class="search-width"
                       v-model="queryParams.classifyCode" placeholder="请选择项目类型">
              <el-option
                  v-for="dict in project_classify"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="签订时间" prop="signTime">
            <el-date-picker class="search-width-middle"
                            v-model="queryParams.signTime"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                            @change="handleParamSignTime">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="甲方名称" prop="principalName">
            <el-input maxlength="50"
                      class="search-width"
                      v-model="queryParams.principalName"
                      placeholder="请输入委托方名称"
                      clearable
                      @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="受托方名称" prop="trusteeName">
            <el-input maxlength="50"
                      class="search-width"
                      v-model="queryParams.trusteeName"
                      placeholder="请输入受托方名称"
                      clearable
                      @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="渠道方" prop="channelName">
            <el-input maxlength="50"
                      class="search-width"
                      v-model="queryParams.channelName"
                      placeholder="请输入渠道方"
                      clearable
                      @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="项目状态" prop="projectStatus">
            <el-select filterable clearable
                       class="search-width"
                       v-model="queryParams.projectStatus" placeholder="请选择项目状态">
              <el-option
                  v-for="dict in project_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="录入部门" prop="deptId">
            <el-tree-select filterable clearable class="search-width"
                            v-model="queryParams.deptId"
                            :data="enabledDeptOptions"
                            :props="{ value: 'id', label: 'label', children: 'children' }"
                            value-key="id"
                            placeholder="请选择录入部门"
                            check-strictly/>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="履约部门" prop="enforceDeptId">
            <el-tree-select filterable clearable class="search-width"
                            v-model="queryParams.enforceDeptId"
                            :data="enabledDeptOptions"
                            :props="{ value: 'id', label: 'label', children: 'children' }"
                            value-key="id"
                            placeholder="请选择履约部门"
                            check-strictly/>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="录入人" prop="userName">
            <el-input maxlength="50"
                      class="search-width"
                      v-model="queryParams.userName"
                      placeholder="请输入录入人"
                      clearable
                      @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="项目负责人" prop="transactorName">
            <el-input maxlength="50"
                      class="search-width"
                      v-model="queryParams.transactorName"
                      placeholder="请输入项目负责人"
                      clearable
                      @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item label="收款时间" prop="receiptTime">
            <el-date-picker class="search-width-middle"
                            v-model="queryParams.receiptTime"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                            @change="handleParamReceiptTime">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="6" :xl="6">
          <el-form-item style="margin-left: 20px">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['biz:bizProject:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['biz:bizProject:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['biz:bizProject:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['biz:bizProject:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Sort"
            @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      <el-tooltip class="item" effect="dark" content="排序" placement="top">
        <el-button circle icon="Operation" style="margin-left: 7px" @click="sortStatus()"/>
      </el-tooltip>
      <div class="sortbox" v-if="showSort">
        <el-text>排序方式：</el-text>
        <el-checkbox v-model="createTimeSortCheck" size="large" @change="changeSort">
          <el-text>创建时间</el-text>
          <el-switch
              v-model="createTimeSort"
              inline-prompt active-text="倒序" inactive-text="正序" @change="changeSort"
          />
        </el-checkbox>
        <el-checkbox v-model="prioritySortCheck" size="large" @change="changeSort">
          <el-text>优先级</el-text>
          <el-switch
              v-model="prioritySort"
              inline-prompt active-text="倒序" inactive-text="正序" @change="changeSort"
          />
        </el-checkbox>
        <el-checkbox v-model="deadlineSortCheck" size="large" @change="changeSort">
          <el-text>预估交付时间</el-text>
          <el-switch
              v-model="deadlineSort"
              inline-prompt active-text="倒序" inactive-text="正序" @change="changeSort"
          />
        </el-checkbox>
        <el-checkbox v-model="totalAmountSortCheck" size="large" @change="changeSort">
          <el-text>合同金额</el-text>
          <el-switch
              v-model="totalAmountSort"
              inline-prompt active-text="倒序" inactive-text="正序" @change="changeSort"
          />
        </el-checkbox>
        <el-checkbox v-model="realAmountSortCheck" size="large" @change="changeSort">
          <el-text>实得额</el-text>
          <el-switch
              v-model="realAmountSort"
              inline-prompt active-text="倒序" inactive-text="正序" @change="changeSort"
          />
        </el-checkbox>
      </div>
    </el-row>

    <el-table v-loading="loading||loading3||loading4||loading5||loading6||loading7" :data="bizProjectList" border
              :row-class-name="tableRowClassName"
              header-row-class-name="project-table"
              @row-dblclick="handleView"
              v-if="refreshTable"
              :default-expand-all="isExpandAll"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left"/>
      <el-table-column type="expand" width="40">
        <template #default="props">
          <el-table :data="props.row.topicList"
                    :row-class-name="topicRowClassName"
                    @row-dblclick="showDetail"
                    style="width:calc(100vw - 90px)"
                    border>
            <el-table-column label="序号" align="left" prop="indexNum" width="60"/>
            <el-table-column label="课题名称" align="left" prop="topicName" show-overflow-tooltip/>
            <el-table-column label="状态" align="left" prop="statusName" width="150"/>
            <el-table-column label="截止完成时间" align="left" prop="endTime" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="负责人" align="left" prop="managerName" width="100"/>
            <el-table-column label="当前跟进部门" align="left" prop="deptName" width="180"/>
            <el-table-column label="创建人" align="left" prop="userName" width="100"/>
            <el-table-column label="创建时间" align="left" prop="createTime" width="180"/>
            <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="150">
              <template #default="scope">
                <el-tooltip content="流转" placement="top" v-if="scope.row.status==1">
                  <el-button link type="primary" icon="RefreshLeft" @click="handleTopicSet(scope.row,0)"
                             v-hasPermi="['biz:bizTopic:replace']">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="完成" placement="top" v-if="scope.row.status==1">
                  <el-button link type="primary" icon="Finished" @click="handleTopicSet(scope.row,1)"
                             v-hasPermi="['biz:bizTopic:done']">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="开始" placement="top" v-if="scope.row.status==0">
                  <el-button link type="primary" icon="Pointer" @click="handleStart(scope.row)"
                             v-hasPermi="['biz:bizTopic:start']">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleTopicUpdate(scope.row)"
                             v-hasPermi="['biz:bizTopic:edit']">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleTopicDelete(scope.row)"
                             v-hasPermi="['biz:bizTopic:remove']">
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" align="left" width="50"/>
      <el-table-column label="优先级" align="left" prop="priority" width="100" show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="project_priority" :value="scope.row.priority"/>
        </template>
      </el-table-column>
      <el-table-column label="签订时间" align="left" prop="signTime" width="120" show-overflow-tooltip/>
      <el-table-column label="项目级别" align="left" prop="level" width="100" show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="project_level" :value="scope.row.level"/>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="left" prop="projectName" min-width="250" show-overflow-tooltip/>
      <el-table-column label="项目区域" align="left" prop="locationTxt" width="180" show-overflow-tooltip/>
      <el-table-column label="项目类型" align="left" prop="classifyCode" show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="project_classify" :value="scope.row.classifyCode"/>
        </template>
      </el-table-column>
      <el-table-column label="项目板块" align="left" prop="sectorName" width="160" show-overflow-tooltip/>
      <el-table-column label="合同类型" align="left" prop="contractTypeCode" show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="contract_type" :value="scope.row.contractTypeCode"/>
        </template>
      </el-table-column>
      <el-table-column label="甲方名称" align="left" prop="principalName" width="200" show-overflow-tooltip/>
      <el-table-column label="受托方" align="left" prop="trusteeName" width="200" show-overflow-tooltip/>
      <el-table-column label="开票状态" align="left" prop="realAmount" width="120">
        <template #default="scope">
          <span>{{ scope.row.invoiceMoney < scope.row.totalAmount ? '未完成' : '已完成' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收款状态" align="left" prop="realAmount" width="120">
        <template #default="scope">
          <span>{{ scope.row.receivedAmount < scope.row.totalAmount ? '未完成' : '已完成' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实得额" align="left" prop="realAmount" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.realAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同额" align="left" prop="totalAmount" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.totalAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已收款" align="left" prop="receivedAmount" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.receivedAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="未收款" align="left" prop="unReceivedAmount" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.unReceivedAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预估成本" align="left" prop="baseCost" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.baseCost) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预估税前利润" align="left" prop="profit" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.profit) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预估技术绩效" align="left" prop="performance" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.agreePerformance) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预估市场绩效" align="left" prop="marketPerformance" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.marketPerformance) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预估净利润" align="left" prop="finalProfit" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.finalProfit) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="全额回款日" align="left" prop="receiptAllDate" width="120" show-overflow-tooltip/>
      <el-table-column label="技术履约评价" align="left" prop="createScore" width="120" show-overflow-tooltip/>
      <el-table-column label="市场履约评价" align="left" prop="managerScore" width="120" show-overflow-tooltip/>
      <el-table-column label="项目状态" align="left" prop="projectStatus" width="160">
        <template #default="scope">
          <dict-tag v-if="scope.row.projectStatus!=98" :options="project_status" :value="scope.row.projectStatus"/>
          <text v-if="scope.row.projectStatus==98">已完成，底稿已归档</text>
        </template>
      </el-table-column>
      <el-table-column label="履约部门" align="left" prop="deptName" width="100" show-overflow-tooltip/>
      <el-table-column label="项目负责人" align="left" prop="transactorName" width="100" show-overflow-tooltip/>
      <el-table-column label="创建人" align="left" prop="userName" width="100" show-overflow-tooltip/>
      <el-table-column label="创建时间" align="left" prop="createTime" width="180"/>
      <el-table-column fixed="right" label="操作" align="left" width="150">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                      v-if="checkPermi(['biz:bizProject:edit']) && scope.row.editAuth">
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-if="checkPermi(['biz:bizProject:remove']) && scope.row.editAuth">
            </el-button>
          </el-tooltip>
          <el-dropdown style="margin-left: 12px">
            <el-button link type="primary" icon="More">
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeStatus'])" icon="Sort"
                                  @click="handleSet(scope.row,0)">修改项目状态
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:submit']) && scope.row.projectStatus===0"
                                  icon="Check"
                                  @click="doUpdateStatus(scope.row,1)">提交
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.createScoreAuth"
                                  icon="Notification"
                                  @click="handleScore(scope.row,0)">技术履约评价
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.managerScoreAuth"
                                  icon="Notification"
                                  @click="handleScore(scope.row,1)">市场履约评价
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeTransactor'])" icon="User"
                                  @click="handleSet(scope.row,3)">项目负责人
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeDept'])" icon="RefreshLeft"
                                  @click="handleSet(scope.row,2)">项目流转
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeLevel'])" icon="Sort"
                                  @click="handleSet(scope.row,1)">设置优先级
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:invoice'])" icon="Tickets"
                                  @click="handleInvoice(scope.row)">开票信息维护
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:topic'])" icon="Notebook"
                                  @click="handleTopicAdd(scope.row)">子课题维护
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:team'])" icon="ChatLineRound"
                                  @click="handleTeam(scope.row)">团队成员
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeZg'])" icon="Lock"
                                  @click="doUpdateZg(scope.row)">转总工办
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeSf'])
                && scope.row.projectStatus===1" icon="Warning"
                                  @click="doUpdateStatus(scope.row,3)">转司法
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeTj'])
                && (scope.row.projectStatus===1 || scope.row.projectStatus===2)" icon="Open"
                                  @click="doUpdateStatus(scope.row,4)">成果提交
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeDg'])
                && (scope.row.projectStatus >= 99)" icon="Open"
                                  @click="doUpdateStatus(scope.row,98)">底稿移交
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeWc'])
                && scope.row.projectStatus!==100" icon="Check"
                                  @click="doUpdateStatus(scope.row,100)">项目完成
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['biz:bizProject:changeZz'])
                && scope.row.projectStatus!==99" icon="Close"
                                  @click="doUpdateStatus(scope.row,99)">项目终止
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="open" width="1500px" append-to-body
               @close="cancel">
      <el-form ref="bizProjectRef" :model="form" :rules="allRules" label-width="120px" :validate-on-rule-change="false">
        <el-collapse v-model="activeNames">
          <el-collapse-item title="项目基本信息" name="t1">
            <el-row>
              <el-col :span="8">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input maxlength="200" :disabled="view" class="input-width" v-model="form.projectName"
                            placeholder="请输入项目名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目类型" prop="classifyCode">
                  <el-select filterable clearable :disabled="view" v-model="form.classifyCode"
                             placeholder="请选择项目类型">
                    <el-option
                        class="input-width"
                        v-for="dict in project_classify"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同金额" prop="totalAmount">
                  <CurrencyInput :disabled="view" class="input-width" v-model="form.totalAmount"
                                 placeholder="请输入合同金额"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属板块" prop="sectorId">
                  <el-cascader :disabled="view" filterable clearable
                               class="input-width"
                               v-model="form.sectorAll"
                               :options="bizSectorList"
                               :props="{value: 'id',label:'name'}"
                               :show-all-levels="false"
                               @change="handleChangeSector"></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('contractTypeCode')">
                <el-form-item label="合同类型" prop="contractTypeCode">
                  <el-select filterable clearable :disabled="view" v-model="form.contractTypeCode"
                             placeholder="请选择合同类型">
                    <el-option
                        v-for="dict in contract_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('signTime')">
                <el-form-item label="签订时间" prop="signTime">
                  <el-date-picker :disabled="view"
                                  class="input-width"
                                  clearable
                                  v-model="form.signTime"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  :disabled-date="disabledDate"
                                  placeholder="请选择签订时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('signAddr')">
                <el-form-item label="签订地点" prop="signAddr">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.signAddr"
                            placeholder="请输入签订地点"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('realAmount')">
                <el-form-item label="实得额" prop="realAmount">
                  <CurrencyInput :disabled="view" class="input-width" v-model="form.realAmount"
                                 placeholder="请输入实得额"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('assessment')">
                <el-form-item label="评估标的" prop="assessment">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.assessment"
                            placeholder="请输入评估标的"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('auditee')">
                <el-form-item label="被审计单位" prop="auditee">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.auditee"
                            placeholder="请输入被审计单位"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('termAll')">
                <el-form-item label="合同期限" prop="termAll">
                  <el-date-picker :disabled="view"
                                  class="input-width"
                                  v-model="form.termAll"
                                  type="daterange"
                                  range-separator="至"
                                  start-placeholder="开始日期"
                                  end-placeholder="结束日期"
                                  format="YYYY-MM-DD"
                                  value-format="YYYY-MM-DD"
                                  @change="handleTime">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('level')">
                <el-form-item label="项目级别" prop="level">
                  <el-select filterable clearable :disabled="view" v-model="form.level" placeholder="请选择项目级别">
                    <el-option
                        v-for="dict in project_level"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('priority')">
                <el-form-item label="优先级" prop="priority">
                  <el-select filterable clearable :disabled="view" v-model="form.priority" placeholder="请选择优先级">
                    <el-option
                        v-for="dict in project_priority"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('location')">
                <el-form-item label="项目建设地区" prop="location">
                  <el-cascader :disabled="view" filterable clearable
                               class="input-width"
                               v-model="form.location"
                               :options="bizAreaList"
                               :props="{value: 'name',label:'name'}"></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('investment')">
                <el-form-item label="项目总投资" prop="investment">
                  <CurrencyInput :disabled="view" class="input-width" v-model="form.investment"
                                 placeholder="请输入项目总投资"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('specialName')">
                <el-form-item label="专项名称" prop="specialName">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.specialName"
                            placeholder="请输入专项名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('reviewer')">
                <el-form-item label="评审人" prop="reviewer">
                  <el-select filterable
                             :disabled="view" class="input-width" v-model="form.reviewer"
                             multiple
                             remote
                             :remote-method="remoteExpert"
                             :loading="expertLoading"
                             collapse-tags
                             collapse-tags-tooltip
                             :max-collapse-tags="4"
                             placeholder="请选择评审人">
                    <el-option
                        v-for="item in expertOptionList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.name"
                    />
                    <template #header>
                      <el-button type="primary" text bg size="small" @click="addExpert">
                        新增专家
                      </el-button>
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('declareYear')">
                <el-form-item label="申报年度" prop="declareYear">
                  <el-date-picker
                      class="input-width"
                      :disabled="view"
                      v-model="form.declareYear"
                      type="year"
                      placeholder="请选择申报年度"
                      value-format="YYYY"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('financeAmount')">
                <el-form-item label="融资额" prop="financeAmount">
                  <CurrencyInput :disabled="view" class="input-width" v-model="form.financeAmount"
                                 placeholder="请输入融资额"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('assessed')">
                <el-form-item label="被评估单位" prop="assessed">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.assessed"
                            placeholder="请输入被评估单位"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="渠道方信息" name="t2">
            <el-row>
              <el-col :span="8" v-if="fields.includes('channelContacts')">
                <el-form-item label="联系人" prop="channelContacts">
                  <el-select filterable clearable :disabled="view"
                             v-model="form.channelId"
                             allow-create
                             @blur="blurChannel"
                             @clear="clearChannel"
                             placeholder="请选择联系人">
                    <el-option
                        v-for="item in channelList"
                        :key="item.id"
                        :label="item.contacts"
                        :value="item.id"
                        @click.native="changeChannel(item)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('channelPhone')">
                <el-form-item label="联系电话" prop="channelPhone">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.channelPhone"
                            placeholder="请输入联系电话"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="委托方信息" name="t3"
                            v-if="fields.includes('principalName')
                                ||fields.includes('principalLocation')
                                ||fields.includes('principalUsci')
                                ||fields.includes('principalAddr')
                                ||fields.includes('principalContacts')
                                ||fields.includes('principalPhone')">
            <el-row>
              <el-col :span="8" v-if="fields.includes('principalName')">
                <el-form-item label="委托方" prop="principalName">
                  <el-input v-if="view" maxlength="50" disabled class="input-width" v-model="form.principalName"
                            placeholder="委托方"/>
                  <el-select v-if="!view"  filterable clearable
                             v-model="form.principalId"
                             allow-create
                             @blur="blurPip"
                             @clear="clearPip"
                             placeholder="请选择委托方">
                    <el-option
                        v-for="item in invoiceHeaderList"
                        :key="item.id"
                        :label="item.companyName"
                        :value="item.id"
                        @click.native="changePip(item)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('principalUsci')">
                <el-form-item label="组织机构代码" prop="principalUsci">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.principalUsci"
                            placeholder="请输入组织机构代码"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('principalLocation')">
                <el-form-item label="所属区域" prop="principalLocation">
                  <el-cascader :disabled="view" filterable clearable
                               class="input-width"
                               v-model="form.principalLocation"
                               :options="bizAreaList"
                               :props="{value: 'name',label:'name'}"></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('principalAddr')">
                <el-form-item label="详细地址" prop="principalAddr">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.principalAddr"
                            placeholder="请输入地址"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('principalContacts')">
                <el-form-item label="经办人" prop="principalContacts">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.principalContacts"
                            placeholder="请输入经办人"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('principalPhone')">
                <el-form-item label="联系电话" prop="principalPhone">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.principalPhone"
                            placeholder="请输入委托方联系电话"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="受托方信息"
                            v-if="fields.includes('trusteeName')||fields.includes('trusteeContacts')||fields.includes('trusteePhone')"
                            name="t4">
            <el-row>
              <el-col :span="8" v-if="fields.includes('trusteeName')">
                <el-form-item label="受托方" prop="trusteeName">
                  <el-select filterable clearable :disabled="view"
                             v-model="form.trusteeId"
                             @clear="clearTrustee"
                             placeholder="请选择受托方">
                    <el-option
                        v-for="item in trusteeList"
                        :key="item.id"
                        :label="item.companyName"
                        :value="item.id"
                        @click.native="changeTrustee(item)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('trusteeContacts')">
                <el-form-item label="联系人" prop="trusteeContacts">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.trusteeContacts"
                            placeholder="请输入受托方联系人"/>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="fields.includes('trusteePhone')">
                <el-form-item label="联系电话" prop="trusteePhone">
                  <el-input maxlength="50" :disabled="view" class="input-width" v-model="form.trusteePhone"
                            placeholder="请输入受托方联系电话"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="服务内容"
                            v-if="fields.includes('serviceContent')||fields.includes('requirements')||fields.includes('deadline')"
                            name="t5">
            <el-form-item label="服务内容" v-if="fields.includes('serviceContent')" prop="serviceContent">
              <el-input maxlength="500" :disabled="view" class="input-width" v-model="form.serviceContent"
                        type="textarea"
                        placeholder="请输入内容"/>
            </el-form-item>
            <el-form-item label="成果及要求" v-if="fields.includes('requirements')" prop="requirements">
              <el-input maxlength="500" :disabled="view" class="input-width" v-model="form.requirements" type="textarea"
                        placeholder="请输入内容"/>
            </el-form-item>
            <el-form-item label="预估交付时间" v-if="fields.includes('deadline')" prop="deadline">
              <el-date-picker clearable :disabled="view"
                              v-model="form.deadline"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择预估交付时间">
              </el-date-picker>
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="进度款计划时间" v-if="fields.includes('progress')" name="t6">
            <el-button v-if="!view" type="primary" @click="progressAdd()" style="margin-bottom: 20px"><i
                class="el-icon-plus"/>新增
            </el-button>
            <el-table
                :data="form.progressList" style="width: 100%;margin-bottom: 20px">
              <el-table-column prop="stage" label="阶段" width="180"/>
              <el-table-column prop="time" label="时间" width="180"/>
              <el-table-column prop="money" label="款项金额" width="180"/>
              <el-table-column label="操作" v-if="!view">
                <template #default="scope">
                  <el-button
                      size="small"
                      @click="progressEdit(scope.row)">编辑
                  </el-button>
                  <el-button
                      size="small"
                      type="danger"
                      @click="progressDelete(scope.row)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
          <el-collapse-item title="开票进度计划时间" v-if="fields.includes('invoice')" name="t7">
            <el-button v-if="!view" type="primary" @click="invoiceAdd()" style="margin-bottom: 20px"><i
                class="el-icon-plus"/>新增
            </el-button>
            <el-table
                :data="form.invoiceList" style="width: 100%;margin-bottom: 20px">
              <el-table-column prop="stage" label="款项名称" width="180"/>
              <el-table-column prop="time" label="时间" width="180"/>
              <el-table-column label="操作" v-if="!view">
                <template #default="scope">
                  <el-button
                      size="small"
                      @click="invoiceEdit(scope.row)">编辑
                  </el-button>
                  <el-button
                      size="small"
                      type="danger"
                      @click="invoiceDelete(scope.row)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
          <el-collapse-item title="履约部门" name="t8">
            <el-row>
              <el-col :span="8">
                <el-form-item label="履约部门" prop="enforceDeptId">
                  <el-tree-select filterable :disabled="view" class="input-width"
                                  v-model="form.enforceDeptId"
                                  :data="enabledDeptOptions"
                                  :props="{ value: 'id', label: 'label', children: 'children' }"
                                  value-key="id"
                                  placeholder="请选择履约部门"
                                  check-strictly/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="!view">
          <el-button type="primary" @click="submitForm(false)">保 存</el-button>
          <el-button v-if="form.projectStatus==0" type="primary" @click="submitForm(true)">保存并提交</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" draggable
               :title="progressData.id?'修改进度款计划时间':'新增进度款计划时间'" v-model="openProgress" width="500px"
               append-to-body style="margin-top: 200px!important;">
      <el-form ref="progressForm" :model="progressData" :rules="rules" label-width="100px">
        <el-form-item label="阶段" prop="stage">
          <el-input maxlength="50" v-model="progressData.stage" placeholder="请输入阶段"/>
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-date-picker
              class="input-width"
              clearable
              v-model="progressData.time"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="款项金额" prop="moneyCheck">
          <CurrencyInput v-model="progressData.money" placeholder="请输入款项金额"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="progressSubmit">确 定</el-button>
          <el-button @click="progressCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" draggable
               :title="invoiceData.id?'修改开票进度计划时间':'新增开票进度计划时间'" v-model="openInvoice" width="500px"
               append-to-body style="margin-top: 200px!important;">
      <el-form ref="invoiceForm" :model="invoiceData" :rules="rules" label-width="100px">
        <el-form-item label="款项名称" prop="stage">
          <el-input maxlength="50" v-model="invoiceData.stage" placeholder="请输入款项名称"/>
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-date-picker
              class="input-width"
              clearable
              v-model="invoiceData.time"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="invoiceSubmit">确 定</el-button>
          <el-button @click="invoiceCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" draggable :title="'团队成员'" v-model="openTeam" width="500px"
               append-to-body style="margin-top: 200px!important;">
      <el-button type="primary" @click="teamAdd()" style="margin-bottom: 20px"><i
          class="el-icon-plus"/>新增
      </el-button>
      <el-table :data="teamList" style="width: 100%;margin-bottom: 20px" v-loading="teamLoading">
        <el-table-column prop="userName" label="姓名" width="180"/>
        <el-table-column prop="deptName" label="部门" width="180"/>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
                size="small"
                type="danger"
                @click="teamDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button @click="teamCancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" draggable :title="titles[setType]" v-model="openSet" width="500px"
               append-to-body
               style="margin-top: 200px!important;">
      <el-form label-width="100px">
        <el-form-item v-if="setType===0" label="项目状态">
          <el-select filterable clearable v-model="form.projectStatus" placeholder="请选择项目状态">
            <el-option
                class="input-width"
                v-for="dict in project_status"
                :key="dict.value"
                :label="dict.label"
                :value="Number(dict.value)"
                :disabled="dict.value==0"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="setType===1" label="优先级">
          <el-select filterable clearable v-model="form.priority" placeholder="请选择优先级">
            <el-option
                class="input-width"
                v-for="dict in project_priority"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="setType===2" label="履约部门" prop="enforceDeptId">
          <el-tree-select filterable class="input-width"
                          v-model="form.enforceDeptId"
                          :data="enabledDeptOptions"
                          :props="{ value: 'id', label: 'label', children: 'children' }"
                          value-key="id"
                          placeholder="请选择履约部门"
                          check-strictly/>
        </el-form-item>
        <el-form-item v-if="setType===3" label="经办人" prop="transactorId">
          <el-button class="input-width" @click="openSelectUser">{{ form.transactorName || '请选择经办人' }}</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="setSave">确 定</el-button>
          <el-button @click="setCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" draggable :title="scoreForm.type==0?'技术履约评价':'市场履约评价'"
               v-model="openScore" width="500px"
               append-to-body
               style="margin-top: 200px!important;">
      <el-form label-width="100px"
               :rules="rules">
        <el-form-item label="打分" prop="score">
          <el-input-number
              class="input-width"
              v-model="scoreForm.score"
              :min="80"
              :max="100"
              :step="1"
              :controls="false"
              suffix="%"
              :placeholder="请输入分数"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="scoreSave">确 定</el-button>
          <el-button @click="scoreCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <topicAdd ref="topicAddRef" :projectId="topicProjectId" :topicId="topicAddId" @ok="updateTopicOk"/>
    <topicDetail ref="topicDetailRef" :topicId="topicDetailId"/>
    <topicSet ref="topicSetRef" :topicId="topicSetId" :setType="setTopicType" @ok="updateTopicOk"/>
    <selectUser ref="selectRef" :auth="true" @ok="handleSelectUser"/>
    <selectUser ref="selectRef2" :selectNum="-1" @ok="handleTeamUser"/>
    <expertAdd ref="expertAddRef" :id="null" @ok="getListAllExpert"/>
  </div>
</template>

<script setup name="BizProject">
import {
  listBizProject,
  getBizProject,
  delBizProject,
  addBizProject,
  updateBizProject,
  updateStatus,
  updateZg,
  updateScore
} from "@/api/biz/bizProject";
import {deptTreeSelectAll} from "@/api/system/user";
import {listBizArea} from "@/api/biz/bizArea";
import {getConfig, listBizSector} from "@/api/biz/bizSector";
import {listAllExpert} from "@/api/biz/bizExpert";
import {listAllChannel} from "@/api/biz/bizChannel";
import {listAllTrustee} from "@/api/biz/bizTrustee";
import {ElMessage} from "element-plus";
import CurrencyInput from '@/components/CurrencyInput.vue';
import {currentDate} from '@/utils/dateutil';
import {getProjectDefault} from '@/api/api'
import {delBizTopic, startTopic} from "@/api/biz/bizTopic";
import topicAdd from "@/views/biz/bizTopic/topicAdd.vue";
import topicDetail from "@/views/biz/bizTopic/topicDetail.vue";
import topicSet from "@/views/biz/bizTopic/topicSet.vue";
import selectUser from "@/views/system/user/selectUser.vue";
import {checkPermi} from "@/utils/permission";
import {formatMoney} from '@/utils/money';
import expertAdd from "@/views/biz/bizExpert/expertAdd.vue";
import {listAllInvoiceHeader} from "@/api/biz/bizInvoiceHeader.js";
import {addBizProjectTeam, delBizProjectTeam, listAllBizProjectTeam} from "@/api/biz/bizProjectTeam.js";

const router = useRouter();
const {proxy} = getCurrentInstance();
const {
  project_priority,
  project_level,
  project_status,
  project_classify,
  contract_type
} = proxy.useDict('project_status', 'project_classify'
    , 'contract_type', 'project_level', 'project_priority');


const teamLoading = ref(false);
const teamList = ref([]);
const trusteeList = ref([]);
const channelList = ref([]);
const invoiceHeaderList = ref([]);
const expertList = ref([]);
const expertOptionList = ref([]);
const progressData = ref({});
const invoiceData = ref({});
const expertLoading = ref(false);
const openProgress = ref(false);
const openInvoice = ref(false);
const openTeam = ref(false);
const openSet = ref(false);
const openScore = ref(false);
const setType = ref(0);
const activeNames = ref(["t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"]);
const bizProjectList = ref([]);
const open = ref(false);
const view = ref(false);
const loading = ref(true);
const loading3 = ref(true);
const loading4 = ref(true);
const loading5 = ref(true);
const loading6 = ref(true);
const loading7 = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const enabledDeptOptions = ref(undefined);
const deptOptions = ref(undefined);
const fields = ref([]);
const allRules = ref({});
const showSort = ref(false);
const createTimeSortCheck = ref(true);
const createTimeSort = ref(true);
const prioritySortCheck = ref(false);
const prioritySort = ref(false);
const deadlineSortCheck = ref(false);
const deadlineSort = ref(false);
const totalAmountSortCheck = ref(false);
const totalAmountSort = ref(false);
const realAmountSortCheck = ref(false);
const realAmountSort = ref(false);
const topicProjectId = ref(0);
const topicAddId = ref(0);
const topicDetailId = ref(0);
const topicSetId = ref(0);
const setTopicType = ref(0);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const selectId = ref(0);
const titles = ref(["修改项目状态", "修改优先级", "项目流转", "指派经办人"]);
const scoreForm = ref({})

const data = reactive({
  locationValue: [],
  bizAreaList: [],
  bizSectorList: [],
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: null,
    sectorCode: null,
    classifyCode: null,
    principalName: null,
    trusteeName: null,
    projectStatus: null,
    sectorAll: [],
    createTimeSort: true,
    deptId: null,
    enforceDeptId: null,
    userName: null,
    transactorName: null,
    channelName: null,
    receiptTimeStart: null,
    receiptTimeEnd: null,
    signTimeStart: null,
    signTimeEnd: null,
  },
  rules: {
    projectName: [
      {required: true, message: "项目名称不能为空", trigger: "submit"}
    ],
    sectorId: [
      {required: true, message: "所属板块不能为空", trigger: "submit"}
    ],
    classifyCode: [
      {required: true, message: "项目类型不能为空", trigger: "submit"}
    ],
    enforceDeptId: [
      {required: true, message: "履约部门不能为空", trigger: "submit"}
    ],
    transactorId: [
      {required: true, message: "经办人不能为空", trigger: "submit"}
    ],
    totalAmount: [
      {required: true, message: "合同金额不能为空", trigger: "submit"}
    ],
  }
});

const {
  queryParams, form, rules
  , bizAreaList
  , bizSectorList
} = toRefs(data);

function handleSelectUser(data) {
  form.value.transactorName = data.value[0].nickName;
  form.value.transactorId = data.value[0].userId;
}

/** 打开授权用户表弹窗 */
function openSelectUser() {
  proxy.$refs["selectRef"].show();
}

function changeSort() {
  if (createTimeSortCheck.value) {
    queryParams.value.createTimeSort = createTimeSort.value
  } else {
    queryParams.value.createTimeSort = null;
  }
  if (prioritySortCheck.value) {
    queryParams.value.prioritySort = prioritySort.value
  } else {
    queryParams.value.prioritylSort = null;
  }
  if (deadlineSortCheck.value) {
    queryParams.value.deadlineSort = deadlineSort.value
  } else {
    queryParams.value.deadlineSort = null;
  }
  if (totalAmountSortCheck.value) {
    queryParams.value.totalAmountSort = totalAmountSort.value
  } else {
    queryParams.value.totalAmountSort = null;
  }
  if (realAmountSortCheck.value) {
    queryParams.value.realAmountSort = realAmountSort.value
  } else {
    queryParams.value.realAmountSort = null;
  }
  getList();
}

function sortStatus() {
  showSort.value = !showSort.value;
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  loading4.value = true;
  deptTreeSelectAll().then(response => {
    deptOptions.value = response.data;
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
    loading4.value = false;
  });
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false;
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
}

/** 查询项目信息列表 */
function getList() {
  loading.value = true;
  listBizProject(queryParams.value).then(response => {
    bizProjectList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    location: ["四川省", "达州市", "达川区"],
    principalLocation: ["四川省", "达州市", "达川区"],
    createTime: null,
    updateTime: null,
    deleted: null,
    projectName: null,
    sectorCode: null,
    contractTypeCode: null,
    classifyCode: '0',
    addrProvince: null,
    addrCity: null,
    addrArea: null,
    investment: null,
    termStart: null,
    termEnd: null,
    totalAmount: null,
    signTime: null,
    signAddr: null,
    financeAmount: null,
    specialName: null,
    reviewer: null,
    declareYear: null,
    assessed: null,
    auditee: null,
    assessment: null,
    channelId: null,
    channelContacts: null,
    channelPhone: null,
    principalId: null,
    principalName: null,
    principalArea: null,
    principalAddr: null,
    principalUsci: null,
    principalContacts: null,
    principalPhone: null,
    trusteeId: null,
    trusteeName: null,
    trusteeContacts: null,
    trusteePhone: null,
    serviceContent: null,
    requirements: null,
    deadline: null,
    enforceDeptId: null,
    manager: null,
    members: null,
    realAmount: null,
    projectStatus: '0',
    progressList: [],
    invoiceList: [],
    receivedAmount: null,
    transactorId: null,
    transactorName: null,
    level: null,
    priority: null,
    createScore:null,
    managerScore:null,
  };
  allRules.value = rules.value;
  proxy.resetForm("bizProjectRef");
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.sectorId = null;
  handleParamReceiptTime(null);
  handleParamSignTime(null);
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  view.value = false;
  open.value = true;
  title.value = "添加项目信息";
  getProjectDefault().then(response => {
    form.value.enforceDeptId = response.data.defaultDept;
    form.value.contractTypeCode = response.data.defaultContractType;
    form.value.level = response.data.defaultLevel;
    form.value.priority = response.data.defaultPriority;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  view.value = false;
  const _id = row.id || ids.value
  initProject(_id);
  title.value = "修改项目信息";
}

function handleView(row) {
  reset();
  view.value = true;
  initProject(row.id);
  title.value = "查看项目信息";
}

function initProject(_id) {
  getBizProject(_id).then(response => {
    form.value = response.data;
    if (form.value.sectorId) {
      form.value.sectorAll = [];
      form.value.sectorAll = findPath(form.value.sectorId, bizSectorList.value);
      findConfig(form.value.sectorId);
    }
    form.value.termAll = [];
    if (form.value.termStart) {
      form.value.termAll.push(form.value.termStart);
      form.value.termAll.push(form.value.termEnd);
    }
    open.value = true;
  });
}

function findPath(id, options) {
  for (const option of options) {
    if (option.id === id) {
      return [id]; // 找到最后一级，返回其值
    }
    if (option.children) {
      const childPath = findPath(id, option.children);
      if (childPath.length) {
        return [option.id, ...childPath]; // 返回父级和子级的值
      }
    }
  }
  return []; // 如果没有找到，返回空数组
}

/** 提交按钮 */
function submitForm(submit) {
  if (form.value.realAmount && form.value.totalAmount) {
    if (form.value.realAmount > form.value.totalAmount) {
      proxy.$modal.msgError("实得额不能大于合同金额");
      return;
    }else if (form.value.realAmount < form.value.totalAmount && !form.value.channelContacts) {
      proxy.$modal.msgError("请选择渠道方信息");
      return;
    }
  } else {
    if (!form.value.realAmount && form.value.totalAmount && form.value.realAmount!==0) {
      form.value.realAmount = form.value.totalAmount;
    }
  }
  proxy.$refs["bizProjectRef"].validate(valid => {
    if (valid) {
      if (submit) {
        form.value.projectStatus = 1;
      }
      if (form.value.id != null) {
        updateBizProject(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          init();
        });
      } else {
        addBizProject(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          init();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除项目数据项？').then(function () {
    return delBizProject(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('biz/bizProject/export', {
    ...queryParams.value
  }, `项目信息-${currentDate()}.xlsx`)
}

function getListBizArea() {
  listBizArea({}).then(response => {
    bizAreaList.value = proxy.handleTree(response.data, "id", "pid");
  });
}

function getListBizSector() {
  loading3.value = true;
  listBizSector(queryParams.value).then(response => {
    bizSectorList.value = proxy.handleTree(response.data, "id", "parentId");
    loading3.value = false;
  });
}

function progressSubmit() {
  proxy.$refs["progressForm"].validate(valid => {
    if (valid) {
      const foundItemDup = form.value.progressList.find(item => item.stage === progressData.value.stage);
      if (!progressData.value.id) {
        if (foundItemDup) {
          ElMessage.error('存在相同阶段！')
        } else {
          openProgress.value = false;
          progressData.value.id = Date.now();
          form.value.progressList.push(progressData.value);
        }
      } else {
        if (foundItemDup && foundItemDup.id !== progressData.value.id) {
          ElMessage.error('存在相同阶段！')
        } else {
          openProgress.value = false;
          const foundItem = form.value.progressList.find(item => item.id === progressData.value.id);
          // 如果找到了该对象，更新其属性
          if (foundItem) {
            Object.assign(foundItem, progressData.value);
          }
        }
      }
    }
  })
}

function progressCancel() {
  openProgress.value = false;
}

function progressAdd() {
  openProgress.value = true;
  progressData.value = {}
}

function progressEdit(row) {
  openProgress.value = true;
  Object.assign(progressData.value, row);
}

function progressDelete(row) {
  proxy.$modal.confirm('是否确认删除进度款计划数据项？').then(function () {
    form.value.progressList = form.value.progressList.filter(item => item.id !== row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function invoiceSubmit() {
  proxy.$refs["invoiceForm"].validate(valid => {
    if (valid) {
      const foundItemDup = form.value.invoiceList.find(item => item.stage === invoiceData.value.stage);
      if (!invoiceData.value.id) {
        if (foundItemDup) {
          ElMessage.error('存在相同款项名称！')
        } else {
          openInvoice.value = false;
          invoiceData.value.id = Date.now();
          form.value.invoiceList.push(invoiceData.value);
        }
      } else {
        if (foundItemDup && foundItemDup.id !== invoiceData.value.id) {
          ElMessage.error('存在相同款项名称！')
        } else {
          openInvoice.value = false;
          const foundItem = form.value.invoiceList.find(item => item.id === invoiceData.value.id);
          // 如果找到了该对象，更新其属性
          if (foundItem) {
            Object.assign(foundItem, invoiceData.value);
          }
        }
      }
    }
  })
}

function invoiceCancel() {
  openInvoice.value = false;
}

function invoiceAdd() {
  openInvoice.value = true;
  invoiceData.value = {}
}

function invoiceEdit(row) {
  openInvoice.value = true;
  Object.assign(invoiceData.value, row);
}

function invoiceDelete(row) {
  proxy.$modal.confirm('是否确认删除开票进度计划数据项？').then(function () {
    form.value.invoiceList = form.value.invoiceList.filter(item => item.id !== row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function handleTime(value) {
  form.value.termStart = null;
  form.value.termEnd = null;
  if (value && value.length > 0) {
    form.value.termStart = value[0];
  }
  if (value && value.length > 1) {
    form.value.termEnd = value[1];
  }
}

function handleParamReceiptTime(value) {
  queryParams.value.receiptTimeStart = null;
  queryParams.value.receiptTimeEnd = null;
  if (value && value.length > 0) {
    queryParams.value.receiptTimeStart = value[0] + " 00:00:00";
  }
  if (value && value.length > 1) {
    queryParams.value.receiptTimeEnd = value[1] + " 23:59:59";
  }
}
function handleParamSignTime(value) {
  queryParams.value.signTimeStart = null;
  queryParams.value.signTimeEnd = null;
  if (value && value.length > 0) {
    queryParams.value.signTimeStart = value[0] + " 00:00:00";
  }
  if (value && value.length > 1) {
    queryParams.value.signTimeEnd = value[1] + " 23:59:59";
  }
}

function handleParamSector(value) {
  queryParams.value.sectorId = null;
  if (value) {
    queryParams.value.sectorId = value[value.length - 1];
  }
}

function handleChangeSector(value) {
  form.value.sectorId = null;
  if (value) {
    form.value.sectorId = value[value.length - 1];
    findConfig(value[value.length - 1]);
  }
}

function findConfig(id) {
  getConfig(id).then(response => {
    fields.value = response.data.fields;
    allRules.value = Object.assign({}, rules.value, response.data.requiredInfo);
  });
}

function doUpdateStatus(row, status) {
  updateStatus({id: row.id, projectStatus: status,oldStatus:row.projectStatus}).then(response => {
    proxy.$modal.msgSuccess("提交成功");
    getList();
  });
}

function doUpdateZg(row) {
  updateZg({id: row.id}).then(response => {
    proxy.$modal.msgSuccess("提交成功");
    getList();
  });
}

function handleSet(row, type) {
  setType.value = type;
  getBizProject(row.id).then(response => {
    form.value = response.data;
    openSet.value = true;
  });
}
function scoreCancel() {
  openScore.value = false;
}
function handleScore(row, type) {
  scoreForm.value.projectId = row.id;
  scoreForm.value.type = type;
  getBizProject(row.id).then(response => {
    form.value = response.data;
    if(type===0){
      scoreForm.value.score = form.value.createScore;
    }else{
      scoreForm.value.score = form.value.managerScore;
    }
    openScore.value = true;
  });
}

function scoreSave(){
  updateScore(scoreForm.value).then(res=>{
    proxy.$modal.msgSuccess("评分成功");
    openScore.value = false;
    getList();
  })
}

function setSave() {
  updateBizProject(form.value).then(response => {
    proxy.$modal.msgSuccess("修改成功");
    openSet.value = false;
    getList();
  });
}

function setCancel() {
  openSet.value = false;
}

function getListAllExpert() {
  loading5.value = true;
  listAllExpert({}).then(response => {
    expertList.value = response.data;
    expertOptionList.value = response.data;
    loading5.value = false;
  });
}

function getListAllTrustee() {
  loading6.value = true;
  listAllTrustee({}).then(response => {
    trusteeList.value = response.data;
    loading6.value = false;
  });
}

function getListAllChannel() {
  loading7.value = true;
  listAllChannel({}).then(response => {
    channelList.value = response.data;
    loading7.value = false;
  });
}

function getListAllInvoiceHeader() {
  listAllInvoiceHeader({}).then(response => {
    invoiceHeaderList.value = response.data;
  });
}

function changeTrustee(row) {
  form.value.trusteeName = row.companyName;
  form.value.trusteeContacts = row.contacts;
  form.value.trusteePhone = row.phone;
}

function clearTrustee() {
  form.value.trusteeName = '';
  form.value.trusteeContacts = '';
  form.value.trusteePhone = '';
}

function blurChannel() {
  if (form.value.channelId && typeof form.value.channelId === 'string') {
    //如果不是数字，则为手动输入
    channelList.value = channelList.value.filter(item => item.id >= 0);
    var t = {
      id: -Date.now(),
      contacts: form.value.channelId,
      phone: ''
    };
    form.value.channelPhone = t.phone;
    form.value.channelContacts = t.contacts;
    form.value.channelId = t.id;
    channelList.value.push(t);
  }
}

function changeChannel(row) {
  form.value.channelContacts = row.contacts;
  form.value.channelPhone = row.phone;
}

function clearChannel() {
  form.value.channelContacts = '';
  form.value.channelPhone = '';
}


function blurPip() {
  if (form.value.principalId && typeof form.value.principalId === 'string') {
    //如果不是数字，则为手动输入
    invoiceHeaderList.value = invoiceHeaderList.value.filter(item => item.id >= 0);
    var t = {
      id: -Date.now(),
      companyName: form.value.principalId,
      usci: "",
      registeredAddr: "",
      contacts: "",
      phone: "",
    };
    form.value.principalName = t.companyName;
    form.value.principalUsci = t.usci;
    form.value.principalAddr = t.registeredAddr;
    form.value.principalContacts = t.contacts;
    form.value.principalId = t.id;
    invoiceHeaderList.value.push(t);
  }
}

function changePip(row) {
  form.value.principalName = row.companyName;
  form.value.principalUsci = row.usci;
  form.value.principalAddr = row.registeredAddr;
  form.value.principalContacts = row.contacts;
  form.value.principalPhone = row.phone;
}

function clearPip() {
  form.value.principalName = '';
  form.value.principalUsci = '';
  form.value.principalAddr = '';
  form.value.principalContacts = '';
  form.value.principalPhone = '';
}

function handleTopicSet(row, type) {
  setTopicType.value = type;
  topicSetId.value = row.id;
  proxy.$refs["topicSetRef"].show();
}

function handleStart(row) {
  proxy.$modal.confirm('是否确认开始[' + row.topicName + ']？').then(function () {
    return startTopic(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("开始成功");
  }).catch(() => {
  });
}

/** 修改按钮操作 */
function handleTopicUpdate(row) {
  topicProjectId.value = null;
  topicAddId.value = row.id;
  nextTick(() => {
    proxy.$refs["topicAddRef"].show();
  });
}

function handleTopicAdd(row) {
  // router.push("/biz/bizTopic?topicProjectId=" + row.id);
  topicProjectId.value = row.id;
  topicAddId.value = null;
  nextTick(() => {
    proxy.$refs["topicAddRef"].show();
  });
}

/** 删除按钮操作 */
function handleTopicDelete(row) {
  proxy.$modal.confirm('是否确认删除子课题数据项？').then(function () {
    return delBizTopic(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function updateTopicOk() {
  getList();
}

function handleInvoice(row) {
  router.push("/biz/bizInvoice?invoiceProjectId=" + row.id);
}

function showDetail(row) {
  topicDetailId.value = row.id;
  proxy.$refs["topicDetailRef"].show();
}


// 蓝色动态计算
function getBlueColor(row) {
  // 提前提醒颜色渐变（示例预设5种蓝色）
  const blueGradient = [
    ' l8-row', // 5天前
    ' l7-row', // 4天前
    ' l6-row', // 3天前
    ' l5-row', // 2天前
    ' l4-row'  // 1天前/当天
  ];
  if(row.projectStatus == 2){
    return blueGradient[4];
  }
  const dueDate = new Date(row.deadline);
  const today = new Date();
  const diffDays = Math.ceil((dueDate - today) / (1000 * 60 * 60 * 24));
  if(diffDays<=0){
    return blueGradient[4];
  }
  if(diffDays>5){
    if(row.priority=='1'){
      return ' success-row'
    }else{
      return '';
    }
  }
  return blueGradient[Math.min(diffDays-1, 4)];
}

// 辅助方法：判断是否逾期30天
function isOverdue30Days(row) {
  if(row.projectStatus != 2){
    return false;
  }
  const overdueDays = Math.floor((new Date() - new Date(row.deadline)) / (1000 * 60 * 60 * 24));
  return overdueDays > 30;
}

const tableRowClassName = ({row, rowIndex}) => {
  let className = 'project-table';
  if (!row.topicList || row.topicList.length == 0) {
    className += ' icon-no';
  }
  // 优先级判断（从高到低）
  if (row.projectStatus == 3) {
    //转司法
    className += ' error-row';      // 红色最高
  }else if (row.zgAuth) {
    //总工办
    className += ' warning-row';    // 橙色次之
  }else if(row.projectStatus == 2 || row.projectStatus == 1){
    if (isOverdue30Days(row)) {
      className += ' l3-row';       // 黄色第三
    }else{
      className +=getBlueColor(row);
    }
  }
  return className;
}
const topicRowClassName = ({row, rowIndex}) => {
  if (row.due && row.status != 2) {
    return 'error-row'
  }
  if (row.warn && row.status != 2) {
    return 'warning-row'
  }
  return ''
}

function addExpert() {
  proxy.$refs["expertAddRef"].show();
}

const remoteExpert = (query) => {
  if (query) {
    expertLoading.value = true;
    setTimeout(() => {
      expertLoading.value = false;
      expertOptionList.value = expertList.value.filter((item) => {
        return item.name.toLowerCase().includes(query.toLowerCase()) || item.phone.toLowerCase().includes(query.toLowerCase());
      })
    }, 200)
  } else {
    expertOptionList.value = []
  }
}

function teamAdd() {
  proxy.$refs["selectRef2"].show();
}

function handleTeamUser(data) {
  const ids = data.value.map(obj => obj.userId);
  addBizProjectTeam({projectId: selectId.value, userIds: ids}).then(response => {
    getListBizProjectTeam();
  });
}

function teamDelete(row) {
  proxy.$modal.confirm('是否确认删除子课题数据项？').then(function () {
    return delBizProjectTeam(row.id);
  }).then(() => {
    getListBizProjectTeam();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function teamCancel() {
  openTeam.value = false;
}

function handleTeam(row) {
  selectId.value = row.id;
  openTeam.value = true;
  getListBizProjectTeam();
}

function getListBizProjectTeam() {
  teamLoading.value = true;
  listAllBizProjectTeam({projectId: selectId.value}).then(response => {
    teamList.value = response.data;
    teamLoading.value = false;
  });
}


function init() {
  getList();
  getListBizArea();
  getListBizSector();
  getDeptTree();
  getListAllExpert();
  getListAllTrustee();
  getListAllChannel();
  getListAllInvoiceHeader();
}

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

allRules.value = rules.value;
init();
</script>
<style scoped>
.sortbox {
  height: 30px;
  margin-left: 5px;
  display: flex;
  align-items: center;
}

::v-deep .icon-no .el-table__expand-icon {
  display: none;
}

::v-deep .el-table .el-table__body .project-table td:nth-child(2) {
  border-right: none;
}

::v-deep .el-table .el-table__body .project-table td:nth-child(3) .cell {
  padding-left: 0;
}

::v-deep .el-table .el-table__header-wrapper .project-table th:nth-child(2) {
  border-right: none;
}

::v-deep .el-table--default .project-table th:nth-child(3) .cell {
  padding-left: 0;
  margin-left: -5px;
}
</style>
<style>
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-8);
  color: #000000;
}
.el-table .error-row {
  --el-table-tr-bg-color: var(--el-color-error-light-3);
  color: #000000;
}

.el-table .warning-row {
  --el-table-tr-bg-color: #ff9800;
  color: #000000;
}

.el-table .l3-row {
  --el-table-tr-bg-color: #ffbe5c;
  color: #000000;
}
.el-table .l4-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-5);
  color: #000000;
}
.el-table .l5-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-6);
  color: #000000;
}
.el-table .l6-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-7);
  color: #000000;
}
.el-table .l7-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-8);
  color: #000000;
}
.el-table .l8-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-9);
  color: #000000;
}
</style>
